using AutoMapper;
using MediatR;
using Microsoft.AspNetCore.Mvc;
using B.S.RbacData.ErrorCode;
using SupplierCustomerManagement.Read.API.Applications.Commands.attachments;
using SupplierCustomerManagement.Read.API.Dtos;

namespace SupplierCustomerManagement.Read.API.Controllers
{
    /// <summary>
    /// 附件查询控制器
    /// </summary>
    [ApiController]
    [Route("api/[controller]/[action]")]
    public class AttachmentsController : ControllerBase
    {
        private readonly IMediator _mediator;
        private readonly IMapper _mapper;
        private readonly ILogger<AttachmentsController> _logger;

        public AttachmentsController(
            IMediator mediator,
            IMapper mapper,
            ILogger<AttachmentsController> logger)
        {
            _mediator = mediator;
            _mapper = mapper;
            _logger = logger;
        }

        /// <summary>
        /// 获取附件列表
        /// </summary>
        /// <param name="pageIndex">页码（从1开始）</param>
        /// <param name="pageSize">每页大小</param>
        /// <param name="relatedEntityId">关联实体ID</param>
        /// <param name="relatedEntityType">关联实体类型</param>
        /// <returns>分页查询结果</returns>
        [HttpGet]
        public async Task<ApiPaging<AttachmentListDto>> GetAttachments(
            int pageIndex = 1,
            int pageSize = 10,
            int? relatedEntityId = null,
            string? relatedEntityType = null)
           
        {
            try
            {
                _logger.LogInformation("开始查询附件列表，页码: {PageIndex}, 每页大小: {PageSize}", pageIndex, pageSize);

                var query = new GetAttachmentsQuery
                {
                    PageIndex = pageIndex,
                    PageSize = pageSize,
                    RelatedEntityId = relatedEntityId,
                    RelatedEntityType = relatedEntityType,
                   
                };

                var result = await _mediator.Send(query);

                if (result.code == ResultEnumCode.Ok)
                {
                    _logger.LogInformation("附件列表查询成功，总数量: {TotalCount}, 当前页数量: {CurrentPageCount}", 
                        result.TotalCount, result.PageData?.Count);
                }
                else
                {
                    _logger.LogWarning("附件列表查询失败，错误信息: {Message}", result.message);
                }

                return result;
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, "查询附件列表时发生异常");

                return new ApiPaging<AttachmentListDto>
                {
                    code = ResultEnumCode.fails,
                    message = $"查询附件列表时发生异常: {ex.Message}",
                    data = default,
                    TotalCount = 0,
                    PageCount = 0,
                    PageData = new List<AttachmentListDto>()
                };
            }
        }

        
    }
} 